package conversion.plugin;

import conversion.bean.Plugin;
import conversion.service.PluginService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@Service
public class PluginManager {


    @Resource
    private PluginService pluginService;

    public static List<ConvertPlugin> searchPluginClasses(String jarFilePath) {


        List<ConvertPlugin> result = new ArrayList<>();

        try {
            // 创建 JarFile 对象
            JarFile jarFile = new JarFile(jarFilePath);
            // 获取 JarFile 中所有的 JarEntry
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();

                // 只处理以 .class 结尾的文件，并且排除内部类
                if (entryName.endsWith(".class") && !entryName.contains("$")) {
                    String className = entryName.substring(0, entryName.lastIndexOf('.')).replace('/', '.');

                    // 使用 URLClassLoader 加载类
                    URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(jarFilePath).toURI().toURL()});
                    Class<?> clazz = classLoader.loadClass(className);

                    // 检查类是否实现了给定的插件接口
                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> inter : interfaces) {
                        if (ConvertPlugin.class.isAssignableFrom(inter)) {
                            Object instance = clazz.newInstance();
                            ConvertPlugin plugin = (ConvertPlugin) instance;
                            result.add(plugin);
                        }
                    }

                    classLoader.close();
                }
            }

            jarFile.close();
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e ) {
            e.printStackTrace();
        }

        return result;
    }

    //加载已激活的插件
    public  Map<String, Object> loadPlugins() {


        List<ConvertPlugin> classList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();

        List<Plugin> plugins = pluginService.getAllPluginByisLoad(true);

        for (Plugin plugin : plugins) {
            classList.addAll(searchPluginClasses(plugin.getPluginPath()));
        }
        for (ConvertPlugin plugin : classList) {
            map.put(plugin.getInputType().toUpperCase()+"to"+plugin.getOutputType().toUpperCase(),plugin);
        }

        return map;

    }





}
